package com.eqdd.yiqidian.ui.gongneng.kehu;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps2d.model.LatLng;
import com.eqdd.yiqidian.AddKehuActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.AreaBean;
import com.eqdd.yiqidian.bean.rebuild.ClientResultBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditEnterBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditHintBean;
import com.eqdd.yiqidian.bean.utils.MultiChooseBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.map.SelectMapActivity;
import com.eqdd.yiqidian.ui.base.SlimBaseMultiEditActivity;
import com.eqdd.yiqidian.utils.MultiChooseTestUtil;
import com.eqdd.yiqidian.utils.SingleChooseUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.eqdd.yiqidian.widget.ActionSheetDialog;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import chihane.jdaddressselector.BottomDialog;
import chihane.jdaddressselector.ISelectAble;

public class UpdateKehuActivity extends SlimBaseMultiEditActivity {
    private AddKehuActivityCustom dataBinding;

    private static final int RICH_TEXT = 6;

    //private ClientListResultBean kehuBean;
    private HashMap<Integer, String> params;
    private String content;
    private String key;
    private int updataPosition;
    private ActionSheetDialog clientTypeDialog;
    AMapLocation aMapLocation;

    private String updateContent;
    private List<AreaBean> areaBean;
    private BottomDialog areaDialog;
    private StringBuilder result;
    private ClientResultBean items;
    private LatLng latlng;
    private String latAndLong;
    private String quhao;
    private int id;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_add_kehu);
        initTopTitleBar(View.VISIBLE, "客户详情");
        isSave = false;
        id = getIntent().getIntExtra(Config.ID, -1);
    }


    @Override
    protected RecyclerView initRecyclerView() {
        return dataBinding.recyclerView;
    }

    @Override
    public void itemClick(int p) {
        switch (p) {
            case 2:
                if (clientTypeDialog == null) {
                    SingleChooseUtil.getChooseDialog(this, 29,
                            sheetDialog -> {
                                clientTypeDialog = sheetDialog;
                                clientTypeDialog.show();
                            }
                            , (position, strings) -> {
                                key = params.get(p);
                                content = strings.get(position - 1);
                                updataPosition = p;
                                updateContent = strings.get(position - 1);
                                updateParam();
                            }

                    );
                } else {
                    clientTypeDialog.show();
                }
                break;
            case 3:
                if (areaDialog == null) {
                    OkGo.<List<AreaBean>>post(HttpConfig.BASE_URL + HttpConfig.AREA_OPTIONS)
                            .params("type", 0)
                            .cacheMode(CacheMode.IF_NONE_CACHE_REQUEST)
                            .cacheKey(HttpConfig.BASE_URL + HttpConfig.AREA_OPTIONS + "0")
                            .execute(new DialogCallBack<List<AreaBean>>(this) {
                                @Override
                                public void onSuccess(Response<List<AreaBean>> response) {
                                    areaBean = response.body();
                                    initAreaPicker();
                                }

                                @Override
                                public void onCacheSuccess(Response<List<AreaBean>> response) {
                                    super.onCacheSuccess(response);
                                    areaBean = response.body();
                                    initAreaPicker();
                                }
                            });
                } else {
                    areaDialog.show();
                }
                break;
            case 4:
                Bundle bundle = new Bundle();
                bundle.putDouble(Config.LAT, items.getAddrlong());
                bundle.putDouble(Config.LON, items.getAddrlat());
                bundle.putString(Config.AREA_CONTENT, items.getAddress());
                startActivityForResult(SelectMapActivity.class, bundle, Config.SELECT_MAP);
                break;
            case 7:
                break;
        }
    }

    private void initAreaPicker() {
        List<MultiChooseBean> multiChooseBeen = new ArrayList<>();
        multiChooseBeen.addAll(areaBean);
        areaDialog = new MultiChooseTestUtil().getAreaDialog(UpdateKehuActivity.this, 3, multiChooseBeen, (d, a) -> {
            areaDialog.dismiss();
            result = new StringBuilder();
            for (ISelectAble iSelectAble : a) {
                result.append(iSelectAble.getName());
            }
            if (((AreaBean) a.get(1).getArg()).getCode().equals("0")) {
                quhao = ((AreaBean) a.get(2).getArg()).getQucode();
            } else {
                quhao = ((AreaBean) a.get(1).getArg()).getCode();
            }
            key = params.get(3);
            content = result.toString();
            updataPosition = 3;
            updateContent = result.toString();
            updateParam();
        });
        areaDialog.show();
    }

    @Override
    protected void setEditBeans() {
        if (params == null) {
            params = new HashMap<>();
            params.put(1, "cusName");
            params.put(2, "cusType");
            params.put(3, "salesTerritory");
            params.put(4, "address");
            params.put(5, "cusCall");
            params.put(6, "url");
            params.put(7, "remark");
        }
        OkGo.<HttpResult<ClientResultBean>>post(HttpConfig.BASE_URL + HttpConfig.CLENT_INFO)
                .params("owner", user.getGuid())
                .params("cusid", id)
                .execute(new DialogCallBack<HttpResult<ClientResultBean>>(this) {
                    @Override
                    public void onSuccess(Response<HttpResult<ClientResultBean>> response) {
                        HttpResult<ClientResultBean> httpResult = response.body();
                        if (httpResult.getStatus() == 200) {
                            items = httpResult.getItems();
                            datas.clear();
                            datas.add(new SlimEditHintBean("客户编码", items.getCusCode(), 0));
                            datas.add(new SlimEditEnterBean("客户名称", items.getCusName(), 1, ""));
                            datas.add(new SlimEditEnterBean("客户类型", items.getCusType(), 2, true, ""));
                            datas.add(new SlimEditEnterBean("销售区域", items.getSalesTerritory(), 3, true, ""));
                            datas.add(new SlimEditEnterBean("地址", items.getAddress(), 4, true, ""));
                            datas.add(new SlimEditEnterBean("客户电话", items.getCusCall(), 5, ""));
                            datas.add(new SlimEditEnterBean("网址", items.getUrl(), 6, ""));
                            datas.add(new SlimEditEnterBean("客户图文", items.getRemark(), 7, ""));
                            datas.add(new SlimEditHintBean("创建时间", items.getCreateTime(), 8));

                            slimAdapterEx.updateData(datas);
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Config.INTENT_CONTENT) {
            content = data.getStringExtra("content");
            key = params.get(requestCode);
            updataPosition = requestCode;
            updateContent = content;
            updateParam();
        } else if (resultCode == Config.SUCCESS) {
            switch (requestCode) {
                case Config.SELECT_MAP:
                    latlng = data.getParcelableExtra(Config.MAP_RESULT_LOCATION);
                    latAndLong = latlng.longitude + "," + latlng.latitude;
                    String map = data.getStringExtra(Config.MAP_RESULT_STRING);
                    key = params.get(4);
                    content = map + "";
                    updataPosition = 4;
                    updateContent = map;
                    updateParam();
                    break;
            }
        }
    }

    private void updateParam() {
        PostRequest<HttpResult> params = OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.UPDATE_CLIENT)
                .params("owner", user.getGuid())
                .params("cusid", id)
                .params("data", formatParam());
        params.execute(new DialogCallBack<HttpResult>(this) {
            @Override
            public void onSuccess(Response<HttpResult> response) {
                HttpResult httpResult = response.body();
                ToastUtil.showShort(httpResult.getMsg());
                if (httpResult.getStatus() == 200) {
                    datas.get(updataPosition).setContent(updateContent);
                    slimAdapterEx.notifyItemChanged(updataPosition);
                }
            }
        });
    }

    private String formatParam() {
        HashMap<String, String> map = new HashMap<>();
        map.put(key, content);
        if (key.equals("address")) {
            map.put("latAndLong", latAndLong);
        }
        return new Gson().toJson(map);
//
//        if (!key.equals("address")) {
//            return String.format("{\"%s\":\"%s\"}", key, content);
//        } else {
//            return String.format("{\"%s\":\"%s\",\"latAndLong\":\"%s\"}", key, content, latAndLong);
//        }
    }
}
